package com.tianxin.workbao.workBao.Activity;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.LineUp;
import com.tianxin.workbao.workBao.bean.Loader;
import com.tianxin.workbao.workBao.bean.LoaderUse;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.LineUpProvide;
import com.tianxin.workbao.workBao.dataProvide.LoaderUseProvide;
import com.tianxin.workbao.workBao.holder.SelectLoaderPopupWindowHolder;
import com.tianxin.workbao.workBao.listener.MyPopupWindowListener;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.SPUtils;
import com.tianxin.workbao.workBao.utils.common.TimeUtils;

import java.util.Date;

/**
 * Created by hacker on 2017/6/22.
 */

public class LoadCarOptionActivity extends BaseActivity implements View.OnClickListener, UpdateListViewListener {

    private TextView secondTime;
    private TextView minuteTime;
    private Button startBtn;
    private Button finishBtn;
    private ImageView giveUPLoader;
    private TextView selectLoaderLabel;
    private TextView loaderName;
    private int loaderId;
    private Integer oldLoaderId;
    private ImageView selectLoaderBtn;
    private NestedScrollView nestedScrollView;
    private TextView carNumberTV;
    private TextView coalNameTV;
    private TextView driverNameTV;
    private TextView driverPhoneTV;
    private TextView customerTV;
    private TextView lineUpUserTV;
    private TextView lineUpTimeTV;
    private Handler handler;

    private boolean isStartLoadCar = false; //是否已经开始装车
    private LineUp mLineUp;
    private Loader mLoader;
    private LoaderUse currUseLoader;
    private Handler timeHandler;
    private boolean isPaused = false;
    private boolean isFree = false;
    private int timeUsedInsec;
    private LineUpProvide lineUpProvide;
    private PopupWindow mPopupWindow;
    private MyPopupWindowListener mPopupWindowListener;
    private SelectLoaderPopupWindowHolder popupWindowHolder;
    private long firstTime;
    private boolean isCheck;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.load_car_option);
        super.initStatusBar(true);
        initData();

        initView();

        initEvent();

        bindView();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    public void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setTitle(mLineUp.getCarnumber() + " " + mLineUp.getCoaltype());
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_action_back_24dp));
        //navigationIcon event
        mToolbar.setNavigationOnClickListener(view -> {
            if (!isStartLoadCar) {
                LoadCarOptionActivity.this.finish();
            } else {
                getSweetAlertDialog(LoadCarListActivity.activity).showError("警告", "该车辆还未装车完成，该页面不能关闭");
                return;
            }
        });
        nestedScrollView = findViewById(R.id.body);
        secondTime = findViewById(R.id.second_times);
        minuteTime = findViewById(R.id.minute_times);
        startBtn = findViewById(R.id.start_btn);
        finishBtn = findViewById(R.id.finish_btn);
        giveUPLoader = findViewById(R.id.give_up_loader);
        selectLoaderLabel = findViewById(R.id.select_label);
        selectLoaderBtn = findViewById(R.id.select_load_car_btn);
        loaderName = findViewById(R.id.loader_name);

        carNumberTV = findViewById(R.id.car_number);
        coalNameTV = findViewById(R.id.coal_name);
        driverNameTV = findViewById(R.id.driver_name);
        driverPhoneTV = findViewById(R.id.driver_phone);
        customerTV = findViewById(R.id.customer);
        lineUpUserTV = findViewById(R.id.line_up_user);
        lineUpTimeTV = findViewById(R.id.line_up_time);

        initLoadCarMachine();
    }

    @Override
    public void initData() {
        Bundle bundle = getIntent().getBundleExtra("lp");
        mLineUp = (LineUp) bundle.getSerializable("lineUp");
        checkFree();
    }

    /**
     * 检查该磅单 是否被别人正在装车 或者 已经装车
     */
    private void checkFree() {
        isCheck = true;
        getLineUpProvide().checkFree(mLineUp.getId());
    }

    /**
     * 初始化装载机
     */
    private void initLoadCarMachine() {
        LoaderUseProvide loaderUseProvide = new LoaderUseProvide(this, this);
        loaderUseProvide.getCurrUseLoader((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
    }

    @Override
    public void initEvent() {
        startBtn.setOnClickListener(this);
        finishBtn.setOnClickListener(this);
        selectLoaderLabel.setOnClickListener(this);
        selectLoaderBtn.setOnClickListener(this);
        giveUPLoader.setOnClickListener(this);
        timeHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        if (!isPaused) {
                            addTimeUsed();
                            updateClockUI();
                        }
                        timeHandler.sendEmptyMessageDelayed(1, 1000);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    public void bindView() {
        carNumberTV.setText(mLineUp.getCarnumber());
        coalNameTV.setText(mLineUp.getCoaltype());
        driverNameTV.setText(mLineUp.getCarowner());
        driverPhoneTV.setText(mLineUp.getCarconnectphone());
        customerTV.setText(mLineUp.getBuycompany());
        lineUpUserTV.setText(mLineUp.getLineupusername());
        lineUpTimeTV.setText(TimeUtils.parseDateTime(mLineUp.getAddtime()));
    }

    @Override
    public void onBackPressed() {
        if (isStartLoadCar) {
            Toast.makeText(this, "该车辆还未装车完成，该页面不能关闭", Toast.LENGTH_SHORT).show();
        } else {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(this, "再按一次退出装车", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
            } else {
                super.onBackPressed();
            }
        }
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        switch (viewId) {
            //开始装车
            case R.id.start_btn:
                if (loaderId < 1) {
                    showMessage("你还没有选择装载机");
                    return;
                }
                startLoadCar();
                break;
            //结束装车
            case R.id.finish_btn:
                finishLoadCar();
                break;
            case R.id.select_load_car_btn:
            case R.id.select_label:
                showSelectLoaderPage();
                break;
            case R.id.give_up_loader:
                giveUPLoader();
                break;
        }
    }

    /**
     * click to give up loader 点击放弃
     */
    private void giveUPLoader() {
        if (loaderId == 0) {
            getSweetAlertDialog(LoadCarOptionActivity.this).showError(
                    getResources().getString(R.string.alert_info),
                    " 你还没有选择装载机,请选择");
        } else {
            getSweetAlertDialog(LoadCarOptionActivity.this).showConfirming(
                    getResources().getString(R.string.alert_info),
                    "你确定放弃装载机吗?", "是",
                    sweetAlertDialog -> {
                        LoaderUseProvide loaderUseProvide =
                                new LoaderUseProvide(LoadCarOptionActivity.this,
                                        new UpdateListViewListener() {
                                            @Override
                                            public void onRefreshData(Object result) {
                                                if ((int) result == 1) {
                                                    loaderId = 0;
                                                    loaderName.setText(" ");
                                                }
                                            }

                                            @Override
                                            public void onLoadMoreData(Object result) {

                                            }

                                            @Override
                                            public void showMessage(String msg) {
                                                Toast.makeText(LoadCarOptionActivity.this, msg, Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void showProgress() {
                                                getSweetAlertDialog(LoadCarOptionActivity.this).showDialog("", 0);
                                            }

                                            @Override
                                            public void hideProgress() {
                                                getSweetAlertDialog(LoadCarOptionActivity.this).dismiss();
                                            }
                                        });
                        loaderUseProvide.giveUpUseLoader(loaderId);
                    }
            );
        }
    }

    /**
     * 显示 选择装载机的  popupWindow
     */
    private void showSelectLoaderPage() {
        final WindowManager.LayoutParams params = getWindow().getAttributes();

        popupWindowHolder = new SelectLoaderPopupWindowHolder(this, getPopupWindowListener());
        mPopupWindow = new PopupWindow(popupWindowHolder.getContentView(),
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT, true);

        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        //set animation
        mPopupWindow.setOnDismissListener(() -> {
            ValueAnimator animator = ValueAnimator.ofFloat(0.7f, 1f);
            animator.setDuration(500);
            animator.addUpdateListener(valueAnimator -> {
                params.alpha = (float) valueAnimator.getAnimatedValue();
                params.dimAmount = (float) valueAnimator.getAnimatedValue();
                getWindow().setAttributes(params);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            });
            animator.start();
        });
        mPopupWindow.setTouchInterceptor((view, motionEvent) -> false);
        ValueAnimator animator = ValueAnimator.ofFloat(1f, 0.7f);
        animator.setDuration(500);
        animator.addUpdateListener(valueAnimator -> {
            params.alpha = (float) valueAnimator.getAnimatedValue();
            params.dimAmount = (float) valueAnimator.getAnimatedValue();
            getWindow().setAttributes(params);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        });
        mPopupWindow.showAtLocation(nestedScrollView, Gravity.NO_GRAVITY, 0, 300);
        animator.start();

    }

    /**
     * start loader car
     */
    private void startLoadCar() {
        isStartLoadCar = true;
        startTime();
    }

    /**
     * finish loader car
     */
    private void finishLoadCar() {
        isStartLoadCar = false;
        isPaused = true;
        timeUsedInsec = 0;
        if (loaderId < 1) {
            Toast.makeText(this, "没有选择装载机", Toast.LENGTH_SHORT).show();
            return;
        }
        mLineUp.setLoadcarid(loaderId);
        mLineUp.setLoadcarname(loaderName.getText().toString());
        mLineUp.setLoaduserid((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
        mLineUp.setLoadusername(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "no"));
        mLineUp.setIsloadcar(2);
        mLineUp.setLoadtime(new Date());
        getLineUpProvide().saveLoadCarInfo(mLineUp);
    }

    private void startTime() {
        timeHandler.sendEmptyMessageDelayed(1, 1000);
    }

    /**
     * update time and show
     */
    private void updateClockUI() {
        minuteTime.setText(getMin());
        secondTime.setText(getSec());
    }

    public void addTimeUsed() {
        timeUsedInsec = timeUsedInsec + 1;
    }

    public CharSequence getMin() {
        return String.valueOf(timeUsedInsec / 60);
    }

    public CharSequence getSec() {
        int sec = timeUsedInsec % 60;
        return sec < 10 ? "0" + sec : String.valueOf(sec);
    }

    public Handler getHandler() {
        if (handler == null) {
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.arg1) {
                        case Constant.LOADING:
                            getSweetAlertDialog(LoadCarOptionActivity.this).showDialog(Constant.LOADING_MSG, 0);
                            break;
                        case Constant.LOAD_FAILURE:
                            getSweetAlertDialog(LoadCarOptionActivity.this)
                                    .showError(getResources().getString(R.string.alert_info), Constant.LOADING_MSG);
                            break;
                        case Constant.LOADINGED:
                            getSweetAlertDialog(LoadCarOptionActivity.this).dismiss();
                            break;
                    }
                }
            };

        }
        return handler;
    }

    public MyPopupWindowListener getPopupWindowListener() {
        if (mPopupWindowListener == null) {
            mPopupWindowListener = (selectType, id, information) -> {
                if (selectType == Constant.SELECT_TYPE_LOADER && id > 0) {
                    oldLoaderId = loaderId;
                    loaderId = id;
                    loaderName.setText(information);
                    mPopupWindow.dismiss();
                    //占用装载机
                    useLoader();
                } else {
                    getSweetAlertDialog(LoadCarOptionActivity.this).showError(
                            getResources().getString(R.string.alert_info),
                            getResources().getString(R.string.loader_usesing)
                    );
                }
            };
        }
        return mPopupWindowListener;
    }

    /**
     * after the selected ,use loader 选择后占用装载机
     */
    private void useLoader() {
        if (oldLoaderId != loaderId) {
            giveUpUseLoader();
            LoaderUseProvide loaderUseProvide = new LoaderUseProvide(this, null);
            loaderUseProvide.useLoader(loaderId);
        }
    }

    /**
     * after the selected ,use loader 选择后放弃装载机
     */
    private void giveUpUseLoader() {
        LoaderUseProvide loaderUseProvide = new LoaderUseProvide(this, null);
        loaderUseProvide.giveUpUseLoader(loaderId);
    }

    @Override
    public void showMessage(String msg) {
        if ("ok".equals(msg)) {
            if (isCheck) {
                Toast.makeText(this, "可以装车", Toast.LENGTH_SHORT).show();
                isFree = true;
                isCheck = false;
            } else {
                Toast.makeText(this, "装车成功", Toast.LENGTH_SHORT).show();
                this.finish();
            }
        } else if (msg.contains("failure")) {
            if (isCheck) {
                Toast.makeText(this, "不可以装车！\n " + msg.substring(msg.indexOf("failure") + 1), Toast.LENGTH_LONG).show();
                showBtn(false);
                isFree = false;
            } else {
                Toast.makeText(this, "装车失败\n" + msg.substring(msg.indexOf("failure") + 1), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
    }

    private void showBtn(boolean b) {
        if (b) {
            startBtn.setVisibility(View.VISIBLE);
            finishBtn.setVisibility(View.VISIBLE);
        } else {
            startBtn.setVisibility(View.GONE);
            finishBtn.setVisibility(View.GONE);
        }
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("", 1200);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof LoaderUse) {
            currUseLoader = (LoaderUse) result;
            if (currUseLoader != null) {
                loaderId = currUseLoader.getLoaderId();
                loaderName.setText(currUseLoader.getLoaderName());
            } else {
                loaderId = 0;
                loaderName.setText("");
            }
        }
    }

    @Override
    public void onLoadMoreData(Object result) {
    }

    private LineUpProvide getLineUpProvide() {
        if (lineUpProvide == null) {
            lineUpProvide = new LineUpProvide(this, this, 0);
        }
        return lineUpProvide;
    }
}
